﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using OSharp.AspNetCore.SignalR;
using wyxuan.yoyu.Core.IM.Games.Gobang;
using wyxuan.yoyu.Core.IM.Games.Gobang.Dto;

namespace wyxuan.yoyu.Web.Pack
{
    public class IMChatHub : OsharpHub
    {

        //public static ConcurrentBag<IGroupManager> 


        private readonly ILogger<IMChatHub> _logger;
        private readonly IGobangService _gobangService;

        /// <summary>
        /// 初始化一个<see cref="OsharpHub"/>类型的新实例
        /// </summary>
        public IMChatHub(IConnectionUserCache userCache,
               ILoggerFactory loggerFactory,
               IGobangService gobangService
            ) : base(userCache)
        {
            _logger = loggerFactory.CreateLogger<IMChatHub>();
            _gobangService = gobangService;
        }

        /// <summary>
        /// 下棋
        /// </summary>
        /// <param name="message"></param>
        public void PlayChess(string roomId, ChessMan chess)
        {
            var resTuple = _gobangService.Play(roomId, Context.ConnectionId, chess, out string failUserId);

            var userids = _gobangService.GetCurrentPlayIds(roomId);

            Clients.Clients(userids).SendAsync("PlayChessRespones", chess);

            if (resTuple.Item1)
            {
                //胜利 
                Clients.Client(Context.ConnectionId).SendAsync("ChessWin", "狭路相逢勇者胜，英雄，请再接再厉。");
                //失败
                Clients.Client(failUserId).SendAsync("ChessFail", "狭路相逢勇者胜，英雄，请重新来过。");

            }
            else
            {
                SendMessage(Context.ConnectionId, resTuple.Item2);
            }
        }

        /// <summary>
        /// 加入房间
        /// </summary>
        /// <param name="message"></param>
        public void JoinRoom(string roomId, string userName)
        {

            var resTuple = _gobangService.JoinRoom(roomId, Context.ConnectionId, userName);

            if (resTuple.Item1)
            {
                SendMessage(Context.ConnectionId, $"{userName} 加入房间成功！");
            }
            else
            {
                SendMessage(Context.ConnectionId, $"{userName} 加入房间失败：{resTuple.Item2}！");
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="connectionId"></param>
        /// <param name="msg"></param>
        private void SendMessage(string connectionId, string msg)
        {
            Clients.Client(connectionId).SendAsync("SendMessage", msg);
        }

    }
}
